package com.woniu.permissions.service.impl;

import com.woniu.exception.permissions.PermissionsException;
import com.woniu.exception.permissions.PermissionsExceptionCode;
import com.woniu.permissions.mapper.ResourceMapper;
import com.woniu.permissions.mapper.RoleMapper;
import com.woniu.permissions.model.Role;
import com.woniu.permissions.model.RoleResource;
import com.woniu.permissions.mapper.RoleResourceMapper;
import com.woniu.permissions.param.AddRoleResourceParam;
import com.woniu.permissions.service.RoleResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class RoleResourceServiceImpl extends ServiceImpl<RoleResourceMapper, RoleResource> implements RoleResourceService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private ResourceMapper resourceMapper;

    @Resource
    private RoleResourceMapper roleResourceMapper;
    @Override
    public RoleResource addRoleResource(AddRoleResourceParam toBean) {
        Role role = roleMapper.selectById(toBean.getRoleId());
        if (role==null){
            throw new PermissionsException(PermissionsExceptionCode.PERMISSIONS_EXCEPTION_CODE_NO_REPEAT);
        }
        com.woniu.permissions.model.Resource resource = resourceMapper.selectById(toBean.getResourceId());
        if (resource==null){
            throw new PermissionsException(PermissionsExceptionCode.PERMISSIONS_EXCEPTION_CODE_NO_REPEAT);
        }
        RoleResource roleResource = new RoleResource(null, toBean.getRoleId().intValue(), toBean.getResourceId().intValue());
        roleResourceMapper.insert(roleResource);
        return roleResource;
    }

    @Override
    public RoleResource delRoleResource(Long id) {
        RoleResource roleResource = roleResourceMapper.selectById(id);
        if (roleResource==null){
            throw new PermissionsException(PermissionsExceptionCode.PERMISSIONS_EXCEPTION_CODE_NO_REPEAT);
        }
        roleResourceMapper.deleteById(roleResource);
        return roleResource;
    }
}
